<template>
	<div class="blueprint-designer-container">
    <div class="canvas-container">
      <svg 
        ref="svgContainer" 
        class="grid-background" 
        :class="{ 'panning': isPanning }"
        :viewBox="`0 0 ${viewBoxSize.width} ${viewBoxSize.height}`"
        preserveAspectRatio="xMidYMid meet"
        @mousedown="handleCanvasMouseDown"
        @wheel.prevent="handleWheel"
        @dragenter.prevent="handleDragEnter"
        @dragleave.prevent="handleDragLeave"
        @dragover.prevent="handleDragOver"
        @drop.prevent="handleDrop"
        @contextmenu="handleContextMenu"
      >
        
        <rect width="100%" height="100%" fill="url(#grid)"/>
        
			<!-- 内容容器 -->
			<g 
			  class="content-group"
			  :key="workflowStore.state.version"
			  :transform="`translate(${currentPan.x},${currentPan.y})`"
			>
			  <!-- 添加一个缩放组，确保缩放以正确的中心点进行 -->
			  <g :transform="`scale(${scale})`">
				<!-- 3. 渲染组节点 (最底层) -->
				<g id="workflowGroupNode">
				  <workflow-group-node
					v-for="group in workflowStore.state.groups"
					:key="`group-${group.id}-${workflowStore.state.version}`"
					:group="group"
					:selected="workflowStore.state.selectedGroupIds.includes(group.id)"
					:svgContainer="svgContainer"
					:id="`node-${group.id}`"
					@select="workflowStore.selectGroup"
				  />
				</g>

				<!-- 2. 渲染连接线 (中间层) -->
				<g id="linksContainer">
				  <path
					v-for="connection in workflowStore.state.connections"
					:key="connection.id"
					:d="connection.path"
					class="connection-path"
					:selected="workflowStore.state.selectedConnectionIds.includes(connection.id)"
					:stroke="connection.color"
					stroke-width="workflowStore.state.selectedConnectionIds.includes(connection.id) ? 4 : 2"
					fill="none"
					:filter="workflowStore.state.selectedConnectionIds.includes(connection.id) ? 'drop-shadow(0 0 5px rgba(64, 158, 255, 1))' : '' " 
					@click.stop="handleConnectionClick(connection)"
				  />
				</g>

				<!-- 1. 渲染节点 (最顶层) -->
				<g id="cardsContainer">
				  <workflow-node
					v-for="node in workflowStore.state.nodes"
					:key="`node-${node.id}-${workflowStore.state.version}`"
					:node="node"
					:selected="workflowStore.state.selectedNodeIds.includes(node.id)"
					@select="workflowStore.selectNode"
					@port:menu:show="workflowStore.showNodePortMenu"
					@port:menu:hide="workflowStore.hideNodePortMenu"
					:id="`node-${node.id}`"
					:svgContainer="svgContainer"
				  />
				</g>

				<!-- 拖拽预览 -->
				<g 
				  v-if="previewPosition"
				  class="node-preview"
				  :transform="`translate(${previewPosition.x},${previewPosition.y})`"
				>
				  <rect 
					width="150" 
					height="80" 
					:fill="getPreviewColor(draggedNode?.type)" 
					opacity="0.5" 
					rx="4"
				  />
				</g>
			  </g>
			</g>
		</svg>
    </div>
	<BlueprintNodeMenu :svgContainer="svgContainer" ></BlueprintNodeMenu>
	<BlueprintNodePortMenu :svgContainer="svgContainer" ></BlueprintNodePortMenu>
	<BlueprintNodePortInput :svgContainer="svgContainer" ></BlueprintNodePortInput>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive } from 'vue';
import WorkflowNode from './nodes/WorkflowNode.vue';
import WorkflowGroupNode from './nodes/WorkflowGroupNode.vue';
import type {Connection } from '@/stores/workflow';
import { useCanvasPanning } from './composables/useCanvasPanning';
import { useNodeDragging } from './composables/useNodeDragging';
import { useWorkflowStore, type WorkflowStore } from '@/stores/workflow';
import { useKeydownManage } from '@/views/data-manage/workflow/components/composables/useKeydownManage';
import BlueprintNodeMenu from './components/BlueprintNodeMenu.vue';
import BlueprintNodePortMenu from './components/BlueprintNodePortMenu.vue';
import BlueprintNodePortInput from './components/BlueprintNodePortInput.vue';
// Props 定义
interface Props {
  nodes: [];
  connections: [];
  groups:[]
}
const props = defineProps<Props>();
// 组件状态
const svgContainer = ref<SVGSVGElement | null>(null);
const workflowStore: WorkflowStore = useWorkflowStore();



// 使用组合式函数管理画布拖拽
const { 
  isPanning,
  currentPan,
  scale,
  handleCanvasMouseDown,
  handleWheel,
  updateTransform
} = useCanvasPanning(svgContainer);


// 使用组合式函数管理节点拖拽，传入 updateTransform
const { 
  draggedNode,
  previewPosition,
  handleDragEnter,
  handleDragLeave,
  handleDragOver,
  handleDrop,
  setDragOffset
} = useNodeDragging(svgContainer, updateTransform);

// 添加 viewBox 尺寸状态
const viewBoxSize = reactive({
  width: 2000,
  height: 2000
});

// 获取预览节点颜色
const getPreviewColor = (type?: string) => {
  switch (type) {
    case 'condition': return '#2d4052';
    case 'HTTP-Input': return '#2d522d';
    case 'mqtt': return '#522d2d';
    default: return '#2d2d2d';
  }
};

// 鼠标悬停处理
const handleConnectionMouseOver = (connection: Connection) => {
	
	if(!workflowStore.state.selectedConnectionIds.includes(connection.id)){
		const path = document.querySelector(`[d="${connection.path}"]`);
		if (path) {
		  path.setAttribute('stroke', connection.color);
		  path.setAttribute('stroke-width', '4');
		}
	}
};

// 鼠标离开处理
const handleConnectionMouseOut = (connection: Connection) => {
	if(!workflowStore.state.selectedConnectionIds.includes(connection.id)){
		const path = document.querySelector(`[d="${connection.path}"]`);
		if (path) {
		  path.setAttribute('stroke', connection.color);
		  path.setAttribute('stroke-width', '2');
		}
	}
};

/**
 * 鼠标点击连接线
 */
const handleConnectionClick=(connection: Connection)=>{
	workflowStore.selectConnection(connection.id);
	
}


// 添加右键菜单阻止事件
const handleContextMenu = (e: MouseEvent) => {
  e.preventDefault();
};

onMounted(() => {
 workflowStore.state.nodes=props.nodes;
 workflowStore.state.groups=props.groups;
 workflowStore.state.connections=props.connections;
 
 setDragOffset({ x: 75, y: 40 }); // 根据节点大小的一半设置偏移
  if (svgContainer.value) {
    const rect = svgContainer.value.getBoundingClientRect();
    viewBoxSize.width = rect.width;
    viewBoxSize.height = rect.height;
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', updateViewBoxSize);
  updateTransform();
  
  if(svgContainer.value){
  	workflowStore.initWorkflow(svgContainer.value);
  }
});

onUnmounted(() => {
	const keyboardManager = useKeydownManage();
	keyboardManager.disable();
  // 清理工作流存储
  workflowStore.cleanup();
  workflowStore.clearWorkflow();
  
  // 移除事件监听器
  window.removeEventListener('resize', updateViewBoxSize);
  
  // 清理 SVG 内容
  if (svgContainer.value) {
    const contentGroup = svgContainer.value.querySelector('.content-group');
    if (contentGroup) {
      contentGroup.innerHTML = '';
    }
  }
  // 重置状态
  viewBoxSize.width = 2000;
  viewBoxSize.height = 2000;
  currentPan.x = 0;
  currentPan.y = 0;
  
  
});

const updateViewBoxSize = () => {
  if (svgContainer.value) {
    const rect = svgContainer.value.getBoundingClientRect();
    viewBoxSize.width = rect.width;
    viewBoxSize.height = rect.height;
  }
};

onMounted(() => {
	const keyboardManager = useKeydownManage();
	keyboardManager.enable();
});

</script>

<style lang="scss" scoped>
.blueprint-designer-container {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #1e1e1e;
  color: #fff;

  .canvas-container {
    flex: 1;
    position: relative;
    overflow: hidden;

    .grid-background {
      width: 100%;
      height: 100%;
      background-color: #292929;
      background-image:
        linear-gradient(to right, black 1px, transparent 1px),
        linear-gradient(to bottom, black 1px, transparent 1px),
        linear-gradient(to right, #404040 1px, transparent 1px),
        linear-gradient(to bottom, #404040 1px, transparent 1px);
      background-size: 100px 100px, 100px 100px, 10px 10px, 10px 10px;
      
      // 优化渲染性能
      image-rendering: pixelated;
      backface-visibility: hidden;
      will-change: transform;
      
      &.panning {
        cursor: grabbing !important;
        user-select: none;
      }
      
      // 添加平滑过渡
      transition: background-size 0.1s ease;
      
      .content-group {
        transform-origin: 0 0;
        will-change: transform;
      }
    }
  }
}

.content-wrapper {
  width: 100%;
  height: 100%;
  overflow: hidden;
  pointer-events: none;
}

.content-group {
  transform-origin: 0 0;
  will-change: transform;
  contain: layout style paint;
  transform-box: fill-box;
}

.node-preview {
  pointer-events: none;
  user-select: none;
}

// 修改 WorkflowNode 组件样式
.workflow-node {
  position: absolute;
  width: 150px;
  height: 80px;
  transform-origin: 0 0;
}

.connection-path {
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    filter: drop-shadow(0 0 5px rgba(64, 158, 255, 1));
  }
  
  
}

.global-drag-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

#workflowGroupNode,
#linksContainer,
#cardsContainer {
  pointer-events: all;
}

// 使用 CSS 控制各层的事件响应
.layer-group {
  pointer-events: all;
  
  &:not(:hover) {
    pointer-events: none;
  }
}

.layer-links {
  pointer-events: all;
  
  &:not(:hover) {
    pointer-events: none;
  }
}

.layer-nodes {
  pointer-events: all;
}

// 当拖拽或调整大小时，禁用其他层的事件
.dragging, .resizing {
  ~ .layer-links,
  ~ .layer-nodes {
    pointer-events: none;
  }
}

// 确保组层级正确
.layer-group {
  z-index: 1;
}

.layer-links {
  z-index: 2;
}

.layer-nodes {
  z-index: 3;
}
</style> 